<?php


if (! function_exists('csrf_form_field')) {
    /**
     * Generate a CSRF token form field.
     *
     * @return \Illuminate\Support\HtmlString
     */
    function csrf_form_field()
    {
        return new \Illuminate\Support\HtmlString('<input type="hidden" name="_form_token" value="'.csrf_form_token().'">');
    }
}


if (! function_exists('csrf_form_token')) {
    /**
     * Generate a CSRF token form field.
     *
     * @return \Illuminate\Support\HtmlString
     */
    function csrf_form_token()
    {
        $session = app('session');

        if (isset($session)) {
            $session_token = \Illuminate\Support\Facades\Cache::get($session->token());
            if ($session_token){
                $token=$session_token;
            }else{
                $token =  $session->token().\Faker\Provider\Uuid::uuid();
                \Illuminate\Support\Facades\Cache::forever($session->token(),$token);
            }
            return $token;
        }

        throw new RuntimeException('Application session store not set.');
    }
}

if (! function_exists('check_chage_pwd')) {
    /*************验证密码是否n个月+没改过**************/
    function check_chage_pwd()
    {
        $warning = "";
        $lastUpPwd = auth('admin')->user()->last_up_pwd;
        if (!$lastUpPwd) {
            return '根据安全性要求，首次登录必须修改密码！';
        }
        list($yNow,$mNow) = explode('-',date('Y-m'));
        list($yLast,$mLast) = explode('-',substr($lastUpPwd,0,7));
        $yCha = $yNow-$yLast;
        $mCha = $mNow-$mLast;
        $mChaYq = data_get(getCache('setting'),'pwd_exp_month',3); //要求更新密码的频率
        if($yCha > 0 || $mCha > $mChaYq){
            $warning = $yLast ? ($yCha > 0 ? "您已经{$yCha}年没有更新密码了，强烈建议立即更新！！！" :($mCha >= $mChaYq ? "您已经{$mCha}个月没有更新密码了，建议立即更新！！！" : "")) : "建议更新密码！";
        }
        return $warning;
    }
}

	function tip($msg, $time, $succ_or_err)
	{
		if ($succ_or_err) {
			$face = "Hui-iconfont-face-weixiao";
		}
		else {
			$face = "Hui-iconfont-face-ku";
		}
		return view('common.tipPage', compact('msg', 'time', 'face'));
	}
	
	/* 返回当前的毫秒时间戳 */
	function msectime()
	{
		[
			$msec,
			$sec
		] = explode(' ', microtime());
		$msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
		
		return $msectime;
	}
	
	//datatable控件只把 单引号 进行了转义，“ \ _ % ” 需要自己去转义
	function escape_like_str($str)
	{
		$like_escape_char = "\\";
		$appear_count = substr_count($str, $like_escape_char);
		// dd(str_repeat($like_escape_char, $appear_count));
		return str_replace([
			str_repeat($like_escape_char, $appear_count),
			'%',
			'_'
		], [
			str_repeat($like_escape_char, $appear_count * 2 + 1),
			$like_escape_char . '%',
			$like_escape_char . '_',
		], $str);
	}
	
	/**
	 * 把返回的数据集转换成Tree
	 * @access public
	 *
	 * @param array  $list  要转换的数据集
	 * @param string $pid   parent标记字段
	 * @param string $level level标记字段
	 *
	 * @return array
	 */
	function list_to_tree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
	{
		$tree = [];
		if (is_array($list)) {
			$refer = [];
			foreach ($list as $key => $data) {
				$refer[$data[$pk]] = &$list[$key];
			}
			foreach ($list as $key => $data) {
				$parentId = $data[$pid];
				if ($root == $parentId) {
					$tree[] = &$list[$key];
				}
				else {
					if (isset($refer[$parentId])) {
						$parent = &$refer[$parentId];
						$parent[$child][] = &$list[$key];
					}
				}
			}
		}
		return $tree;
	}
	
	//有序化数字=>数组
	function SerialNumber($numary = [])
	{
		$num = [];
		$count = count($numary);
		sort($numary);
		if ($count > 1) {
			$temp = 0;
			for ($i = 0; $i < $count - 1; $i++) {
				if ($i === 0) {
					$num[$temp][] = $numary[$i];
				}
				$j = $i + 1;
				$temp = $numary[$j] - $numary[$i] === 1 ? $temp : $temp + 1;
				$num[$temp][] = $numary[$j];
			}
		}
		else {
			$num = $numary;
		}
		return $num;
	}
	
	/*有序化数字数组 => 字符串
	$symbol 数字后面带的符号
	*/
	function SerialNumberToStr($num, $symbol = '')
	{
		$str = '';
		foreach ($num as $k => $v) {
			if (is_array($v)) {
				if (count($v) > 1) {
					$str .= ',' . min($v) . $symbol . '～' . max($v) . $symbol;
				}
				else {
					$str .= ',' . $v[0] . $symbol;
				}
			}
			else {
				$str .= ',' . $v . $symbol;
			}
		}
		$str = trim($str, ',');
		return $str;
	}
	
	/**
	 * 获取所有数据库
	 */
	function get_databases()
	{
		$app_names = [];
		foreach (config('database.connections') as $key => $value) {
			# 获取服务器上所有项目的 APP_NAME
			if (strpos($key, 'mysql_') !== false) {
				// str_replace(search,replace,$str)：从$str中查找search用replace来替换
				$app_names[] = str_replace('mysql_', '', $key);
			}
		}
		return $app_names;
	}
	
	/*ajax json 输出*/
	function out($code = 1, $msg = '请求成功', $outdata = [])
	{
		$data = [];
		$data['code'] = $code;
		$data['msg'] = $msg;
		$data['data'] = $outdata;
		return response()->json($data);
	}

	function rtdata($code = 1, $msg = '', $data = []) {
        return ['code' => $code, 'msg' => $msg, 'data' => $data];
    }
	
	//字母（26）进制转10进制(最大支持两位字母)
	function ABC2decimal($abc)
	{
		$abc = strtoupper($abc);
		$abc = str_split($abc);
		$ten = ord($abc[0]) - 64;
		if (count($abc) == 2) {
			$ten = (ord($abc[0]) - 64) * 26 + ord($abc[1]) - 64;
		}
		return $ten;
	}
	
	//10进制 转 字母（26）(最大支持两位字母)
	function dec2ABC($index)
	{
		$str = '';
		$chu = $index / 26;  //除
		if ($int = is_int($chu)) {
			$str = $int == 1 ? 'Z' : chr($chu - 1 + 64) . 'Z';
		}
		else {
			$strStart = floor($chu);
			if ($strStart > 0) {
				$str .= chr($strStart + 64);
			}
			$str .= chr($index % 26 + 64);
		}
		return $str;
	}
	
	
	/**
	 * 返回json_decode处理curl后的结果
	 */
	function deCurl($url, $postData = '', $header = ['Content-type:application/x-www-form-urlencoded'])
	{
		$res = curl($url, $postData, $header);
		return json_decode($res);
	}
	
	/**
	 * curl 访问
	 *
	 * @param $url       链接地址
	 * @param $postData  数组/json传值均可（如果为post请求传值，get请求不需要传值）
	 * @param $header    header头
	 *                   return  返回值(根据参数$format而定，一般为对象）
	 */
	function curl($url, $postData = '', $header = ['Content-type:application/x-www-form-urlencoded'])
	{
		//初始化
		$curl = curl_init();
		//设置抓取的url
		curl_setopt($curl, CURLOPT_URL, $url);
		//设置头文件的信息作为数据流输出
		curl_setopt($curl, CURLOPT_HEADER, 0);
		curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
		// 设置超时限制防止死循环
		curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
		//如果是请求的是https页面，需要添加下面两个参数，规避ssl的证书检查
		if (1 == strpos("$" . $url, "https://")) {
			curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);   // https请求 不验证证书和hosts
			curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		}
		if ($postData) {
			//"content-type: multipart/form-data  post数据用
			if (inArray("content-type: multipart/form-data", $header)) {
				curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);//上传文件或者以上传文件的形式post数据
			}
			curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
			curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
		}
		if ($error = curl_error($curl)) {
			return $error;
		}
		//执行命令
		$data = curl_exec($curl);
		//关闭URL请求
		curl_close($curl);
		return $data;
	}
	
	/*
	*function：计算两个日期相隔多少年，多少月，多少天
	*param string $date1[格式如：2011-11-5]
	*param string $date2[格式如：2012-12-01]
	*return array array('年','月','日');
	*/
	function diffDate($date1, $date2)
	{
		if (strtotime($date1) > strtotime($date2)) {
			$tmp = $date2;
			$date2 = $date1;
			$date1 = $tmp;
		}
		[
			$Y1,
			$m1,
			$d1
		] = explode('-', $date1);
		[
			$Y2,
			$m2,
			$d2
		] = explode('-', $date2);
		$Y = $Y2 - $Y1;
		$m = $m2 - $m1;
		$d = $d2 - $d1;
		if ($d < 0) {
			$d += (int)date('t', strtotime("-1 month $date2"));
			$m--;
		}
		if ($m < 0) {
			$m += 12;
			$Y--;
		}
		return [
			'year'  => $Y,
			'month' => $m,
			'day'   => $d
		];
	}
	
	
	function isAdmin()
	{
		if (!auth('admin')->user()) {
			return false;
		}
		return auth('admin')->user()->id == 1 ? true : false;
	}
	
	function app_name()
	{
		return config('constant.app_name');
	}
	
	/*判断值是否在数组中（不区分大小写）
	@param $value：搜索的值
	@param $array：数组
	*/
	function inArray($value, $array)
	{
		$value = strtolower($value);
		$array = array_map('strtolower', $array);
		return in_array($value, $array);
	}
	
	
	function setCache($key)
	{
		switch ($key) {
			case 'setting':
				$setCon = new \App\Http\Controllers\Admin\SettingController();
				$value = $setCon->setCache();
				break;
		}
		return $value;
	}
	
	function getCache($key)
	{
		return cache($key) ?: setCache($key);
	}
	
	function domain()
	{
		return request()->getHost();
	}
	
	function ary_filter($ary)
	{
		return array_filter($ary, 'ary_filter_back');
	}
	
	function ary_filter_back($val)
	{
		return ($val === '' || $val === null) ? false : true;
	}
	
	function name_admin()
	{
		return '/' . config('constant.name_admin');
	}